package com.securities.stock.utils;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;


/**
 * FastJson工具类
 * @fileName: FastJsonUtils.java
 * @author: Ryan
 */
public class FastJsonUtils {
	private static final SerializeConfig config;

	static {
		config = new SerializeConfig();
		// 使用和json-lib兼容的日期输出格式
		//config.put(java.util.Date.class, new JSONLibDataFormatSerializer());
		// 使用和json-lib兼容的日期输出格式
		//put(java.sql.Date.class, new JSONLibDataFormatSerializer());
		// 使用自定义的日期输出格式
		//config.put(java.util.Date.class, new HuaxinDataFormatSerializer());
	}

	// 输出空置字段
	private static final SerializerFeature[] features = {
		SerializerFeature.WriteMapNullValue,
		// list字段如果为null，输出为[]，而不是null
		SerializerFeature.WriteNullListAsEmpty,
		// 数值字段如果为null，输出为0，而不是null
		SerializerFeature.WriteNullNumberAsZero,
		// Boolean字段如果为null，输出为false，而不是null
		SerializerFeature.WriteNullBooleanAsFalse,
		// 字符类型字段如果为null，输出为""，而不是null
		SerializerFeature.WriteNullStringAsEmpty
	};

	public static String toJSONString(Object object) {
		return JSON.toJSONString(object, config, features);
	}


	public static String toJSONNoFeatures(Object object) {
		return JSON.toJSONString(object, config);
	}

	public static Object toBean(String text) {
		return JSON.parse(text);
	}

	public static <T> T toBean(String text, Class<T> clazz) {
		return JSON.parseObject(text, clazz);
	}
	public static <T> T toBean(String text,TypeReference<T> type) {
		return JSON.parseObject(text, type);
	}

	// 转换为数组
	public static <T> Object[] toArray(String text) {
		return toArray(text, null);
	}

	// 转换为数组
	public static <T> Object[] toArray(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz).toArray();
	}

	// 转换为List
	public static <T> List<T> toList(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz);
	}


	/**
	 * json字符串转化为map
	 * @param str
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map stringToMap(String str) {
		Map m = JSONObject.parseObject(str);
		return m;
	}


	public static ValueFilter filter = new ValueFilter() {
		@Override
		public Object process(Object obj, String s, Object v) {
			return v;
		}
	};

	public static String mapToJSONString(Object object) {
		return JSON.toJSONString(object, config, filter,features);
	}

	/**
	 * 将string转化为序列化的json字符串
	 * 
	 * @param text
	 * @return
	 */
	public static Object textToJson(String text) {
		Object objectJson = JSON.parse(text);
		return objectJson;
	}

}
